<?php

namespace app\dao;

use app\model\UserModel;


class UserDao extends BaseDao
{
    private $query;

    protected function setModel()
    {
        // TODO: Implement setModel() method.
        return UserModel::class;
    }

    public function __construct()
    {
        $this->query = new UserModel();
    }

    public function getAll(){
        try {
        return $this->query->select();
        } catch (\Exception $e) {
            Log::error("获取所有用户失败: " . $e->getMessage());
            return [];
        }
    }

    // 根据用户名获取用户
    public function getUserByUsername($username)
    {
        try {
            return $this->query->where('username', $username)->find();
        } catch (\Exception $e) {
            Log::error("根据用户名获取用户失败: " . $e->getMessage());
            return null;
        }
    }

    // 根据用户 ID 获取用户
    public function getUserById($id)
    {
        try {
            return $this->query->where('id', $id)->find();
        } catch (\Exception $e) {
            Log::error("根据用户ID获取用户失败: " . $e->getMessage());
            return null;
        }
    }

    // 验证用户密码
    public function verifyPassword($username, $password)
    {
        try {
            $user = $this->getUserByUsername($username);
            if ($user && password_verify($password, $user->password)) {
                return $user;
            }
            return null;
        } catch (\Exception $e) {
            Log::error("验证密码失败: " . $e->getMessage());
            return null;
        }
    }

    // 创建新用户
    public function createUser($data)
    {
        try {
            return $this->query->create($data);
        } catch (\Exception $e) {
            Log::error("创建用户失败: " . $e->getMessage());
            return null;
        }
    }
}